<?php
namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Agent\ChaoZongdai;
use App\Models\Log\ChaoMoneyLog;
use App\Models\Order\Order;
use App\Models\Order\WxOrder;
use App\Models\User\BankCard;
use App\Models\User\Record;
use App\Models\User\Tikuan;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $countColumn = "COALESCE(COUNT(t2.id),0)";
        $pmoneyColumn = "COALESCE(SUM(wx_orders.money),0)";
        $tikuanColumn = "COALESCE(SUM(records.money),0)";

        if ($request->ajax()) {

            $User = User::select(
                DB::raw('
                users.id AS "users.id",
                users.nickname AS "users.nickname",
                users.avatar,
                users.money AS "users.money",
                users.phone AS "users.phone",
                users.bindid AS "users.bindid",
                users.income AS "users.income",
                users.reg_time AS "users.reg_time",
                users.zongdai'));

            if ($request->get("sidx") == $pmoneyColumn) {
                $User = $User->leftJoin("wx_orders", function($join) {
                    $join->on("users.id", "=", "wx_orders.user_id")->where("wx_orders.status", "=", 2);
                });
            } else if ($request->get("sidx") == $tikuanColumn) {
                $User = $User->leftJoin("records", function($join) {
                    $join->on("users.id", "=", "records.user_id")->where("records.type", "=", 3);
                });
            } else if ($request->get("sidx") == $countColumn) {
                $User = $User->leftJoin(DB::raw("users AS t2"), "users.id", "=", "t2.bindid");
            }

            $User = $this->filters($request, $User);

            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
                $User = $User->where("users.chao_zongdai", $chaoz->id);
            }

            if ($request->get("bindid")) {
                $User = $User->where("users.bindid", $request->get("bindid"));
            }

            if ($request->get("zongdai")) {
                $User = $User->where("users.zongdai", $request->get("zongdai"))->whereRaw("users.id != users.zongdai");
            }

            if ($request->get("chao_zongdai")) {
                $User = $User->whereRaw("users.zongdai != users.id")
                    ->where("users.chao_zongdai", $request->get("chao_zongdai"));
            }

            $User = $User->groupBy("users.id")->orderBy(DB::raw($request->get("sidx")), $request->get("sord"));

            if (strpos($request->get("sidx"), "users") === false) {
                $User = $User->orderBy("users.id", "ASC");
            }

            $paginator = $User->paginate($request->get("rows"));

            $rows = [];
            foreach ($paginator as $user) {
                $rows[] = $user;
            }

            if ($rows) {

                $column = "users.id";

                $ids = [];
                foreach ($rows as $user) {
                    $ids[] = $user->$column;
                }
//                $bankCards = BankCard::whereIn("user_id", $ids)->get();

                $count = User::whereIn("bindid", $ids)->select("bindid", DB::raw("count(bindid) as c"))->groupBy("bindid")->get();

                $smoney = Order::whereIn("user_id", $ids)->select("user_id", DB::raw("SUM(amounts*num) as amounts"))->groupBy("user_id")->get();

                $payMoneys = WxOrder::select("user_id", DB::raw("SUM(money) AS money"))->whereIn("user_id", $ids)->where("status", 2)->groupBy("user_id")->get();

                $tikuan = Record::select("user_id", DB::raw("SUM(money) AS money"))->whereIn("user_id", $ids)->where("type", 3)->groupBy("user_id")->get();

                foreach ($rows as $user) {
    //                foreach ($bankCards as $val) {
    //                    if ($user->id == $val->user_id) {
    //                        $user->user_name = $val->user_name;
    //                        $user->bank_name = $val->bank_name;
    //                        $user->card_number = $val->card_number;
    //                    }
    //                }
                    $user->smoney = 0;
                    foreach ($smoney as $val) {
                        if ($user->$column == $val->user_id) {
                            $user->smoney = $val->amounts;
                        }
                    }
                    $user->$countColumn = 0;
                    foreach ($count as $val) {
                        if ($user->$column == $val->bindid) {
                            $user->$countColumn = $val->c;
                        }
                    }
                    $user->$pmoneyColumn = 0;
                    foreach ($payMoneys as $val) {
                        if ($user->$column == $val->user_id) {
                            $user->$pmoneyColumn = $val->money;
                        }
                    }
                    $user->$tikuanColumn = 0;
                    foreach ($tikuan as $val) {
                        if ($user->$column == $val->user_id) {
                            $user->$tikuanColumn = -$val->money;
                        }
                    }
                }
            }

            $data = [
                "rows" => $rows,
                "total"=> $paginator->lastPage(),
                "page" => $paginator->currentPage(),
                "records" => $paginator->count(),
            ];

            return response()->json($data);

        } else {

            return view("user/index", [
                "isChaoZongdai" => $this->isChaoZongdai(),
                "countColumn"   => $countColumn,
                "pmoneyColumn"  => $pmoneyColumn,
                "tikuanColumn"  => $tikuanColumn,
                ]);
        }
    }

    public function clearPasswd(Request $request)
    {
        $this->validate($request, [
            "id" => "required|integer",
        ]);

        $id = $request->get("id");

        $user = User::find($id);
        if (!$user) {
            return redirect()->back()->withErrors(["用户不存在"]);
        }

        $user->passwd = "";
        $user->save();

        return response()->json(["success" => true]);
    }

    public function reg(Request $request)
    {
        $date_func = "DATE_FORMAT(`reg_time`,'%Y-%m-%d')";

        if ($request->ajax()) {

            $this->validate($request, [
                "begin_time" => "date",
                "end_time" => "date",
            ]);

            $begin_time = $request->get("begin_time");
            $end_time = $request->get("end_time");

            if (!$begin_time) {
                $begin_time = "1970-01-01";
            }

            if (!$end_time) {
                $end_time = date("Y-m-d") . " 23:59:59";
            } else {
                $end_time = $end_time . " 23:59:59";
            }

            $acc = User::select(
                DB::raw("DATE_FORMAT(`reg_time`,'%Y-%m-%d') AS `date`"),
                DB::raw('COUNT(1) AS "COUNT(1)"'))
                ->whereBetween("reg_time", [$begin_time, $end_time]);

//            $db = DB::connection("skynet")->table("t_users")->whereBetween("reg_time", [$begin_time, $end_time]);

            $acc = $acc->groupBy(DB::raw($date_func));

            $paginator = $acc->orderBy(DB::raw($date_func), $request->get("sord"))->paginate($rows = $request->get("rows"));

            $count = User::count();
            $rows = [];
            foreach ($paginator as $page) {

                $page->count = $count;
                $rows[] = $page;
            }

            $data = [
                "rows" => $rows,
                "total"=> $paginator->lastPage(),
                "page" => $paginator->currentPage(),
                "records" => $paginator->count(),
            ];

            return response()->json($data);

        } else {
            return view("user/reg");
        }
    }

    public function tikuanLog(Request $request)
    {
        $this->validate($request, [
            "begin_time" => "date",
            "end_time"   => "date"
        ]);

        $begin_time = $request->get("begin_time");
        if ($begin_time) {
            $begin_time = date("Y-m-d", strtotime($begin_time));
        }

        $end_time = $request->get("end_time");
        if ($end_time) {
            $end_time = date("Y-m-d", strtotime($end_time)) . " 23:59:59";
        }

        $fee = 5;

        if ($request->ajax()) {
            $Tikuan = Tikuan::where("user_type", 0);

            if ($begin_time) {
                $Tikuan = $Tikuan->where("create_time", ">=", $begin_time);
            }
            if ($end_time) {
                $Tikuan = $Tikuan->where("create_time", "<=", $end_time);
            }

            $Tikuan = $this->filters($request, $Tikuan);

            $paginator = $Tikuan->orderBy($request->get("sidx"), $request->get("sord"))->paginate($request->get("rows"));

            $rows = [];
            foreach ($paginator as $p) {
                $rows[] = $p;
            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];

            return response()->json($data);
        } else {

            return view("user/tikuan", []);
        }
    }

    public function tikuanEdit(Request $request)
    {
        $this->validate($request, [
            "id"     => "required|int",
            "status" => "required|int|min:2|max:3"
        ]);

        $status = $request->get("status");

        $tikuan = Tikuan::find($request->get("id"));

        if ($status == 2) {

        }else if ($status == 3) {

            if ($tikuan->user_type == 0) {
                $user = User::find($tikuan->user_id);

                $old =  $user->money;
                $user->money += $tikuan->rmb * 100;
                $user->save();

                $record = new Record();
                $record->user_id = $user->id;
                $record->before  = $old;
                $record->after   = $user->money;
                $record->money   = $user->money - $old;
                $record->detail  = "提现退款";
                $record->type    =  3;
                $record->create_time = date("Y-m-d H:i:s");
                $record->save();

            } else {
                $user = ChaoZongdai::find($tikuan->user_id);
                $old =  $user->money;
                $user->money += $tikuan->rmb * 100;
                $user->save();

                $record = new ChaoMoneyLog();
                $record->chao_zongdai = $user->id;
                $record->before  = $old;
                $record->after   = $user->money;
                $record->money   = $user->money - $old;
                $record->detail  = "提现退款";
//                $record->type    =  3;
                $record->create_time = date("Y-m-d H:i:s");
                $record->save();
            }

        } else {
            return redirect()->back()->withErrors(["message" => "status 状态只有2,3"]);
        }

        $tikuan->status = $status;
        $tikuan->save();
        return redirect()->back()->withInput(["message" => "审核成功"]);
    }

    public function upZongdai(Request $request)
    {
        if (!$this->isChaoZongdai()) {
            return response()->json(["success" => false , "message" => "合伙人不明确"]);
        }

        $this->validate($request, [
            "id"    => "required|int",
            "zong_ratio" => "int|min:0|max:100"
        ]);

        $ratio = $request->get("zong_ratio");

        $id = $request->get("id");

        DB::beginTransaction();

        $user = User::find($id);
        if (!$user) {
            return response()->json(["success" => false , "message" => "用户不存在"]);
        }

        $admin = Auth::user();
        $chaoZongdai = ChaoZongdai::where("email", $admin->email)->first();
        if ($user->chao_zongdai != $chaoZongdai->id) {
            return response()->json(["success" => false , "message" => "不是你下属用户"]);
        }

        if ($user->zongdai == $user->id) {
            return response()->json(["success" => true]);
        }

        if ($ratio > $chaoZongdai->ratio) {
            return response()->json(["success" => false , "message" => "比率不能大于所属的合伙人"]);
        }

        $user->zongdai      = $user->id;
        $user->bindid       = null;
        $user->zong_ratio   = $ratio;
        $user->chao_zongdai = $chaoZongdai->id;
        $user->save();

        $ids = [$user->id];

        while(1) {

            $affected_rows = User::whereIn("bindid", $ids)->update(["zongdai" => $user->zongdai , "chao_zongdai" => $user->chao_zongdai]);
            if ($affected_rows) {
                $list = User::select("id")->whereIn("bindid", $ids)->get();
                $ids = [];
                foreach ($list as $val) {
                    $ids[] = $val->id;
                }
            } else {
                break;
            }
        }
        DB::commit();
        return response()->json(["success" => true]);
    }


    public function addMoney(Request $request)
    {
        $this->validate($request, [
            "id"    => "required|integer",
            "money" => "required|integer|max:99999999"
        ]);

        $id = $request->get("id");
        $money = (int)$request->get("money");
        if ($this->isChaoZongdai()) {
            return response()->json(["success" => false , "message" => "没有权限"]);
        }
        $user = User::find($id);

        $old = $user->money;
        $user->money += $money * 100;
        $user->save();

        $record = new Record();
        $record->user_id = $user->id;
        $record->before  = $old;
        $record->after   = $user->money;
        $record->money   = $user->money - $old;
        $record->detail  = Auth::user()->email . " 后台转账";
        $record->type    =  4;
        $record->create_time = date("Y-m-d H:i:s");
        $record->save();

        return response()->json(["success" => true]);
    }
}
